//
//  QSSaveImageTool.m
//  Moigem
//
//  Created by apple on 2017/3/9.
//  Copyright © 2017年 Song. All rights reserved.
//

#import "QSSaveImageTool.h"

@implementation QSSaveImageTool
#pragma mark - 将照片保存到沙盒
+ (void)saveImageToSandbox:(UIImage *)image andImageName:(NSString *)imageName andResultBlock:(resultBlock)block
{
    //高保真压缩图片，此方法可将图片压缩，但是图片质量基本不变，第二个参数为质量参数
    NSData *imageData = UIImageJPEGRepresentation(image, 0);
    //将图片写入文件
    NSString *filePath = [self filePath:imageName];
    //是否保存成功
    BOOL result = [imageData writeToFile:filePath atomically:YES];
    //保存成功传值到blcok中
    if (result) {
        block(result);
    }
}

#pragma mark - 从沙盒中读取照片
+ (UIImage *)loadImageFromSandbox:(NSString *)imageName
{
    //获取沙盒路径
    NSString *filePath=[self filePath:imageName];
    //根据路径读取image
    UIImage *image=[UIImage imageWithContentsOfFile:filePath];
    
    return image;
}

#pragma mark - 从沙盒中删除照片
+ (void)deleteImagheWithImageName:(NSString *)imageName
{
    NSFileManager* fileManager=[NSFileManager defaultManager];
    //获取沙盒路径
    NSString *filePath=[self filePath:imageName];
    
    BOOL isHave=[[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!isHave) {
        QSLog(@"no  have");
        return ;
    }else {
        QSLog(@" have");
        BOOL isDelete= [fileManager removeItemAtPath:filePath error:nil];
        if (isDelete) {
            QSLog(@"dele success");
        }else {
            QSLog(@"dele fail");
        }
    }
}

/**
 *  下载图片
 */
+ (void)loadImageWithURLStr:(NSString *)imageUrl finish:(LoadImageFinish)finishBlock
{
    SDWebImageManager *sd_manager = [[SDWebImageManager alloc] init];
    NSURL *url = [NSURL URLWithString:imageUrl];
    [sd_manager downloadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        if (image) {
            finishBlock(image);
        }
    }];
}

#pragma mark - 获取沙盒路径
+(NSString *)filePath:(NSString *)fileName
{
    //获取沙盒目录
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //保存文件名称
    NSString *filePath=[paths[0] stringByAppendingPathComponent:fileName];
    
    return filePath;
}
@end
